//
// Created by sally on 24-10-27.
//

#ifndef ASYNCTHREADPOOL_HPP
#define ASYNCTHREADPOOL_HPP

#pragma once
#include <thread>
#include <chrono>
#include <memory>
#include <array>
#include <list>
#include <functional>

#ifndef USE_BOOST_FUTURE
#include <future>
#else
//#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_VERSION 4
#include "boost/thread/future.hpp"
#endif

#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
#define ASIO_NO_DEPRECATED
#endif

#include "asio/io_context.hpp" 	//io_context use
#include "asio/post.hpp"

#include "Timer_holder.h"

namespace whq::timer
{
#ifndef USE_BOOST_FUTURE
	using namespace std;
#else
	using namespace boost;
#endif

    // 不可移动不可复制类型，异步线程池
    class AsyncThreadPool
    {
    public:
        //直接添加任务
        future<bool> add(std::function<bool()> f)
        {
            packaged_task<bool(void)> pt(std::move(f));
            future<bool> fu = pt.get_future();
            asio::post(ioctx, std::move(pt));
            return fu;
        }
         // 只能单例模式生成
        static AsyncThreadPool& GetInstance()
        {
            static AsyncThreadPool tq;
            return tq;
        }
        // 禁止复制，赋值，移动，移动赋值构造
        AsyncThreadPool(const AsyncThreadPool &) = delete;
        AsyncThreadPool& operator=(const AsyncThreadPool &) = delete;
		AsyncThreadPool(AsyncThreadPool&&) = delete;
		AsyncThreadPool& operator=(AsyncThreadPool&&) = delete;
    private:
        asio::io_context ioctx;
        asio::executor_work_guard<asio::io_context::executor_type> work;

        AsyncThreadPool() : work(ioctx.get_executor())
        {
            int thread_num = 8;
            std::vector<std::thread> processors;
            for (int i = 0; i < thread_num; i++) {
                processors.emplace_back(std::thread([this]{
                    ioctx.run();
                }));
            }
            for (auto &th : processors) {
                th.detach();
            }
        }
    };
}


#endif //ASYNCTHREADPOOL_HPP
